package com.ctg.itrdc.imageconsole.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.itrdc.imageconsole.common.util.PropertiesUtils;

import io.fabric8.kubernetes.api.model.LimitRange;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerList;
import io.fabric8.kubernetes.api.model.ResourceQuota;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.ReplicaSet;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;


/**
 * 	
 * @description: k8s工具类
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年10月12日 上午11:45:35 Piao.Wu v1.0.0 create
 *
 */
public class KubeUtils {

	private static Logger logger = LoggerFactory.getLogger(KubeUtils.class);
	
	private static final String GETKUBEERROR = "Error : getting kube-client failed";

	/**
	 * 
	 * @Description: 获取一个KubernetesClient对象
	 * @author Piao.Wu 2016年10月28日 上午10:26:12
	 * @param apiServerUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return
	 * @throws Exception
	 *             KubernetesClient
	 *
	 */
	private static KubernetesClient getClient(String apiServerUrl) throws Exception 
	{
		if(null == apiServerUrl)
			throw new RuntimeException("Error : parameter apiServerUrl is null, in func getClient(...)");
		return new DefaultKubernetesClient(apiServerUrl);
	}
	
	
	public static String queryNamespace(String apiServerUrl,String namespace){
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "getNamespace.api");
		urlString = MessageFormat.format(urlString, apiServerUrl, namespace);
		
		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("catch exception when queryNamespace ！", e);
		}
		return info;
	}
	
	public static String queryResouceQuota(String apiServerUrl, String namespace,String quotaName){
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "getResourceQuota.api");
		urlString = MessageFormat.format(urlString, apiServerUrl, namespace, quotaName);
		
//		String urlString = "http://"+ apiServerUrl+ "/api/v1/namespaces/" + namespace + "/resourcequotas/" +quotaName;
		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("catch exception when queryResouceQuota ！", e);
		}
		return info;
	}
	
	public static String queryResouceQuotas(String apiServerUrl, String namespace){
//		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "getResourceQuotas.api");
//		urlString = MessageFormat.format(urlString, apiServerUrl, namespace);
		
		String urlString = "http://"+ apiServerUrl+ "/api/v1/namespaces/"+namespace + "/resourcequotas";
		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("catch exception when queryResouceQuota ！", e);
		}
		return info;
	}
	
	
	
	public static NamespaceList queryNamespaces(String apiServerUrl){
		NamespaceList namespaceList = null;
		KubernetesClient kube = null;
		try {
			kube = getClient("http://" + apiServerUrl);
			namespaceList = kube.namespaces().list();
		} catch (Exception e) {
			logger.error("catch exception when queryNamespaces！", e);
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return namespaceList;
	}
	
	public static Namespace createOrUpdateNamespace(String apiServerUrl, String namespace, String yaml) {
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		Namespace namespaceResult = null;
		try {
			jsonIs = new ByteArrayInputStream(yaml.getBytes());
			kube = getClient("http://" + apiServerUrl);
			Namespace namespaceByLoad = kube.namespaces().load(jsonIs).get();
			if (namespaceByLoad == null) {
				throw new RuntimeException("Error: get null Namespace object by jsonIs !");
			}
			if (StringUtils.isNotEmpty(namespace)) {
				namespaceResult = kube.namespaces().withName(namespace).patch(namespaceByLoad);
			} else {
				namespaceResult = kube.namespaces().create(namespaceByLoad);
			}
		} catch (Exception e) {
			logger.error("catch exception when createNamespace!", e);
		} finally {
			try {
				if (kube != null) {
					kube.close();
				}
				jsonIs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return namespaceResult;
	}
	
	public static String deleteNamespace(String apiServerUrl, String namespace) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "getNamespace.api");
		urlString = MessageFormat.format(urlString, apiServerUrl, namespace);
		
//		String urlString = "http://"+ apiServerUrl+ "/api/v1/namespaces/"+namespace;
		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().delete();
				}
			});
		} catch (Exception e) {
			logger.error("catch exception when deleteNamespace ！", e);
		}
		return info;
	}
	
	public static ResourceQuota createOrUpdateResourceQuota(String apiServerUrl, String namespace, String quotaName, String yaml){
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		ResourceQuota quota = null;
		try {
			jsonIs = new ByteArrayInputStream(yaml.getBytes());
			kube = getClient("http://" + apiServerUrl);
			ResourceQuota quotaByLoad = kube.resourceQuotas().load(jsonIs).get();
			if (quotaByLoad == null) {
				throw new RuntimeException("Error: get null ResourceQuota object by jsonIs !");
			}
			if (StringUtils.isNotEmpty(quotaName)) {
				quota = kube.resourceQuotas().inNamespace(namespace).withName(quotaName).patch(quotaByLoad);
			} else {
				quota = kube.resourceQuotas().inNamespace(namespace).create(quotaByLoad);
			}
		} catch (Exception e) {
			logger.error("catch exception when createResourceQuota !", e);
		} finally {
			try {
				if (kube != null) {
					kube.close();
				}
				jsonIs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return quota;
	}
	
	
	public static LimitRange createOrUpdateLimitRange(String apiServerUrl, String namespace, String limitRangeName, String yaml) {
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		LimitRange limitRange = null;
		try {
			jsonIs = new ByteArrayInputStream(yaml.getBytes());
			kube = getClient("http://" + apiServerUrl);
			LimitRange limitRangeByLoad = kube.limitRanges().load(jsonIs).get();
			if (limitRangeByLoad == null) {
				throw new RuntimeException("Error: get null LimitRange object by jsonIs !");
			}
			if (StringUtils.isNotEmpty(limitRangeName)) {
				limitRange = kube.limitRanges().inNamespace(namespace).withName(limitRangeName).patch(limitRangeByLoad);
			} else {
				limitRange = kube.limitRanges().inNamespace(namespace).create(limitRangeByLoad);
			}
		} catch (Exception e) {
			logger.error("catch exception when createLimitRange !", e);
		} finally {
			try {
				if (kube != null) {
					kube.close();
				}
				jsonIs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return limitRange;
	}
	
	
	/**
	 * 
	 * @Description: 判断rc是否存在
	 * @author Piao.Wu 2016年10月28日 上午9:54:54
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return boolean
	 *
	 */
	public static boolean isRcExist(String k8sUrl, String rcName) {
		String rcInfo = KubeUtils.queryRcByApi(k8sUrl, rcName);
		if (rcInfo != null) {
			return true;
		}
		return false;
	}


	/**
	 * 
	 * @Description: rc扩缩容
	 * @author Piao.Wu 2016年10月28日 上午9:57:15
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @param replicas 扩缩容之后的数量
	 * @return boolean
	 *
	 */
	public static boolean updateRcReplicas(String k8sUrl, String namespace, String rcName, int replicas) {
		boolean isSuccess = false;
		KubernetesClient kube = null;
		try {
			kube = getClient(k8sUrl);
			ReplicationController rep = kube.replicationControllers().inNamespace(namespace).withName(rcName)
					.scale(replicas);
			if (rep.getSpec().getReplicas() == replicas) {
				isSuccess = true;
			}
		} catch (Exception e) {
			logger.error("rc在扩缩容时出现异常！", e);
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return isSuccess;
	}

	/**
	 * 
	 * @Description: rc更新
	 * @author Piao.Wu 2016年10月28日 上午9:58:33
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param oldName
	 * @param json
	 * @return boolean
	 *
	 */
	public static boolean updateRC(String k8sUrl, String namespace, String oldName, String json) {
		boolean isSuccess = true;
		InputStream is = null;
		KubernetesClient kube = null;
		try {
			is = new ByteArrayInputStream(json.getBytes());
			kube = getClient(k8sUrl);
			ReplicationController rc = new ReplicationController();
			rc = kube.replicationControllers().load(is).get();
			kube.replicationControllers().inNamespace(namespace).withName(oldName).rolling().replace(rc);
		} catch (Exception e) {
			isSuccess = false;
			logger.error("rc在更新时出现异常！", e);
		} finally {
			try {
				if (kube != null) {
					kube.close();
				}
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return isSuccess;
	}
	

	/**
	 * 
	 * @Description: rc删除（鉴于k8s的接口会存在删除rc后pod还存在的情况，此方法专门用于删除rc后，再删除pod）
	 * @author Piao.Wu 2016年10月28日 上午9:59:17
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return boolean
	 *
	 */
	public static boolean deleteRcAndPod(String k8sUrl, String rcName) {
		boolean isSuccess = false;
		KubernetesClient kube = null;
		try {
			kube = getClient(k8sUrl);
			ReplicationController rc = queryRc(k8sUrl, rcName);
			if (rc.getMetadata() != null) {
				if (kube.replicationControllers().delete(rc)) {
					isSuccess = deletePodsByRc(k8sUrl, rcName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return isSuccess;
	}

	/**
	 * 
	 * @Description: rc删除
	 * @author Piao.Wu 2016年10月28日 上午10:00:27
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return boolean
	 *
	 */
	public static boolean deleteRC(String k8sUrl, String namespace, String rcName) {
		boolean isSuccess = false;
		KubernetesClient kube = null;
		try {
			kube = getClient(k8sUrl);
			ReplicationController rc = queryRc(k8sUrl, rcName);
			if (rc != null) {
				rc.getMetadata().setNamespace(namespace);
				isSuccess = kube.replicationControllers().delete(rc);
			}
		} catch (Exception e) {
			logger.error("rc在删除时出现异常！", e);
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return isSuccess;
	}

	/**
	 * 
	 * @Description: 通过http请求的方式查出所有的pod
	 * @author Piao.Wu 2016年10月28日 上午10:00:39
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return String
	 *
	 */
	public static String queryAllPodByApi(String k8sUrl) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryAllPod.api");
		urlString = MessageFormat.format(urlString, k8sUrl);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAllPodByApi时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 根据pod名称查询pod
	 * @author Piao.Wu 2016年10月28日 上午10:07:55
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param podName
	 * @return Pod
	 *
	 */
	public static Pod queryPod(String k8sUrl, String podName) {
		Pod pod = null;
		PodList pList = queryAllPod(k8sUrl);
		List<Pod> list = pList.getItems();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getMetadata() != null && list.get(i).getMetadata().getName().equals(podName)) {
				pod = list.get(i);
				break;
			}
		}
		return pod;
	}

	/**
	 * 
	 * @Description: 查出集群下面所有的pod
	 * @author Piao.Wu 2016年10月28日 上午10:08:36
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return PodList
	 *
	 */
	public static PodList queryAllPod(String k8sUrl) {
		PodList rlist = null;
		KubernetesClient kube = null;
		try {
			kube = getClient(k8sUrl);
			rlist = kube.pods().list();
		} catch (Exception e) {
			logger.error("queryAllPod时出现异常！", e);
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return rlist;
	}

	/**
	 * 
	 * @Description: 查出rc下面所有的pod
	 * @author Piao.Wu 2016年10月28日 上午10:29:26
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return List<Pod>
	 *
	 */
	public static List<Pod> queryPodsByRcName(String k8sUrl, String rcName) {
		List<Pod> items = new ArrayList<Pod>();
		
		PodList pods = queryAllPod(k8sUrl);
		for (int i = 0, len = pods.getItems().size(); i < len; i++) {
			if ((rcName + "-").equals(pods.getItems().get(i).getMetadata().getGenerateName())) {
				items.add(pods.getItems().get(i));
			}
		}
		return items;
	}

	/**
	 * 
	 * @Description: 通过api的方式查出集群下面的一个pod
	 * @author Piao.Wu 2016年10月28日 上午10:10:22
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param podName
	 * @return String
	 *
	 */
	public static String queryPodByApi(String k8sUrl, String podName) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryPod.api");
		urlString = MessageFormat.format(urlString, k8sUrl, podName);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryPodByApi时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 通过api的方式查出集群下面所有的rc
	 * @author Piao.Wu 2016年10月28日 上午10:11:16
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return String
	 *
	 */
	public static String queryAllRcByApi(String k8sUrl) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryAllRc.api");
		urlString = MessageFormat.format(urlString, k8sUrl);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAllRcByApi时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查出集群下面所有的rc
	 * @author Piao.Wu 2016年10月28日 上午10:14:58
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return ReplicationControllerList
	 *
	 */
	public static ReplicationControllerList queryAllRc(String k8sUrl) {
		ReplicationControllerList rlist = null;
		KubernetesClient kube = null;
		try {
			kube = getClient(k8sUrl);
			rlist = kube.replicationControllers().list();
		} catch (Exception e) {
			logger.error("queryAllRc方法出现异常！", e);
		} finally {
			if (kube != null) {
				kube.close();
			}
		}
		return rlist;
	}

	/**
	 * 
	 * @Description: 查询rc
	 * @author Piao.Wu 2016年10月28日 上午10:16:46
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return ReplicationController
	 *
	 */
	public static ReplicationController queryRc(String k8sUrl, String rcName) {
		ReplicationController rc = new ReplicationController();
		ReplicationControllerList rlist = queryAllRc(k8sUrl);
		for (int i = 0; i < rlist.getItems().size(); i++) {
			if (rlist.getItems().get(i).getMetadata().getName().equals(rcName)) {
				rc = rlist.getItems().get(i);
			}
		}
		return rc;
	}

	/**
	 * 
	 * @Description: 通过api的方式查询rc
	 * @author Piao.Wu 2016年10月28日 上午10:17:21
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return String
	 *
	 */
	public static String queryRcByApi(String k8sUrl, String rcName) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryRc.api");
		urlString = MessageFormat.format(urlString, k8sUrl, rcName);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryRcByApi时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询所有的service
	 * @author Piao.Wu 2016年10月28日 上午10:17:52
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return String
	 *
	 */
	public static String queryAllService(String k8sUrl) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryAllService.api");
		urlString = MessageFormat.format(urlString, k8sUrl);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAllService时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询service
	 * @author Piao.Wu 2016年10月28日 上午10:18:31
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param serviceName
	 * @return String
	 *
	 */
	public static String queryService(String k8sUrl, String serviceName) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryService.api");
		urlString = MessageFormat.format(urlString, k8sUrl, serviceName);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryService时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询所有的node
	 * @author Piao.Wu 2016年10月28日 上午10:18:46
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return String
	 *
	 */
	public static String queryAllNode(String k8sUrl) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryAllNode.api");
		urlString = MessageFormat.format(urlString, k8sUrl);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAllNode时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询node
	 * @author Piao.Wu 2016年10月28日 上午10:19:09
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param nodeName
	 * @return String
	 *
	 */
	public static String queryNode(String k8sUrl, String nodeName) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryNode.api");
		urlString = MessageFormat.format(urlString, k8sUrl, nodeName);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryNode时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询所有的event
	 * @author Piao.Wu 2016年10月28日 上午10:19:21
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @return String
	 *
	 */
	public static String queryAllEvent(String k8sUrl) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryAllEvent.api");
		urlString = MessageFormat.format(urlString, k8sUrl);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAllEvent时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 查询event
	 * @author Piao.Wu 2016年10月28日 上午10:19:48
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param eventName
	 * @return String
	 *
	 */
	public static String queryEvent(String k8sUrl, String eventName) {
		String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "queryEvent.api");
		urlString = MessageFormat.format(urlString, k8sUrl, eventName);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryEvent时出现异常！", e);
		}
		return info;
	}

	/**
	 * 
	 * @Description: 删除rc下面所有的pod
	 * @author Piao.Wu 2016年10月28日 上午10:25:10
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param rcName
	 * @return boolean
	 *
	 */
	public static boolean deletePodsByRc(String k8sUrl, String rcName) {
		boolean isSuccess = false;
		try {
			KubernetesClient kube = getClient(k8sUrl);
			List<Pod> items = queryPodsByRcName(k8sUrl, rcName);
			if (items.size() > 0) {
				isSuccess = kube.pods().delete(items);
			}
		} catch (Exception e) {
			logger.error("deletePods时出现异常！", e);
		}
		return isSuccess;
	}

	/**
	 * 
	 * @Description: 删除pod
	 * @author Piao.Wu 2016年10月28日 上午10:25:51
	 * @param k8sUrl
	 *            k8s的地址 ，例如：http://10.142.90.22:8080
	 * @param podName
	 * @return boolean
	 *
	 */
	public static boolean deletePod(String k8sUrl, String podName) {
		boolean isSuccess = false;
		try {
			KubernetesClient kube = getClient(k8sUrl);
			Pod pod = queryPod(k8sUrl, podName);
			if (pod == null) {
				return true;
			}
			if (pod.getMetadata() != null) {
				isSuccess = kube.pods().delete(pod);
			}
		} catch (Exception e) {
			logger.error("deletePod时出现异常！", e);
		}
		return isSuccess;
	}
	
	public static ReplicationController newRcByJson(String apiServerUrl, String json) 
	{		
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		try 
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new RuntimeException(GETKUBEERROR);
			jsonIs = new ByteArrayInputStream(json.getBytes());
			try
			{
				return kube.replicationControllers().load(jsonIs).get();
			} catch(Exception e){
				throw new RuntimeException("Error : error occured when generating rc java object by yaml, it may be caused by incorrect yaml file. " + e.getMessage());
			}
		} catch (Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {			
			try 
			{
				if(jsonIs != null)
					jsonIs.close();
			} catch (IOException e) {
				
			}	
			if(null != kube)
				kube.close();
		}
	}
	
	private static ReplicationController newRcByJson(KubernetesClient kube, String json) 
	{		
		InputStream jsonIs = null;
		try 
		{				
			jsonIs = new ByteArrayInputStream(json.getBytes());
			try
			{
				return kube.replicationControllers().load(jsonIs).get();
			} catch(Exception e){
				throw new RuntimeException("Error : error occured when generating rc java object by yaml, it may be caused by incorrect yaml file. " + e.getMessage());
			}
		} catch (Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {			
			try 
			{
				if(jsonIs != null)
					jsonIs.close();
			} catch (IOException e) {
				
			}			
		}
	}
	
	private static Deployment newDpByJson(KubernetesClient kube, String json) 
	{		
		InputStream jsonIs = null;
		try 
		{				
			jsonIs = new ByteArrayInputStream(json.getBytes());
			try
			{
				return kube.extensions().deployments().load(jsonIs).get();
			} catch(Exception e){
				throw new RuntimeException("Error : error occured when generating rc java object by yaml, it may be caused by incorrect yaml file. " + e.getMessage());
			}
		} catch (Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {			
			try 
			{
				if(jsonIs != null)
					jsonIs.close();
			} catch (IOException e) {
				
			}			
		}
	}
	
	/*private static Deployment newDeploymentByJson(KubernetesClient kube, String json) 
	{		
		InputStream jsonIs = null;
		try 
		{				
			jsonIs = new ByteArrayInputStream(json.getBytes());
			try
			{
				return kube.extensions().deployments().load(jsonIs).get();
			} catch(Exception e){
				throw new RuntimeException("Error : error occured when generating rc java object by yaml, it may be caused by incorrect yaml file. " + e.getMessage());
			}
		} catch (Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {			
			try 
			{
				if(jsonIs != null)
					jsonIs.close();
			} catch (IOException e) {
				
			}			
		}
	}*/
	
	public static void createRc(String apiServerUrl, String json)
	{		
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		try
		{
			jsonIs = new ByteArrayInputStream(json.getBytes());
			kube = getClient(apiServerUrl);
			if(null == kube)			
				throw new NullPointerException(GETKUBEERROR);					
			ReplicationController rc = newRcByJson(kube, json);
			if(null == rc)		
				throw new NullPointerException("Error : newing rc java object by yaml file returns null");			
			kube.replicationControllers().create(rc);	
			
		} catch(Exception e) {						
			throw new RuntimeException(e.getMessage());			
		} finally {
			if(null != jsonIs)
				try 
				{
					jsonIs.close();
				} catch (IOException e) {
					;//do nothing
				}
			if(null != kube)
				kube.close();
		}		
	}
	
	public static void createDp(String apiServerUrl, String namespace, String json) {
		InputStream jsonIs = null;
		KubernetesClient kube = null;
		try
		{
			jsonIs = new ByteArrayInputStream(json.getBytes());
			kube = getClient(apiServerUrl);
			if(null == kube)			
				throw new NullPointerException(GETKUBEERROR);					
			Deployment dp = newDpByJson(kube, json);
			if(null == dp)		
				throw new NullPointerException("Error : newing dp java object by yaml file returns null");			
			kube.extensions().deployments().create(dp);				
		} catch(Exception e) {						
			throw new RuntimeException(e.getMessage());			
		} finally {
			if(null != jsonIs)
				try 
				{
					jsonIs.close();
				} catch (IOException e) {
					;//do nothing
				}
			if(null != kube)
				kube.close();
		}		
		
	}
	
	public static void deleteRc(String apiServerUrl, String namespace, String rcName)
	{		 
		KubernetesClient kube = null;
		try
		{				
			kube = getClient(apiServerUrl);				
			if(null == kube)						
				throw new NullPointerException(GETKUBEERROR);	
			ReplicationController rc = KubeUtils.getRc(kube, namespace, rcName);
			if(null == rc)
				return;
			kube.replicationControllers().inNamespace(namespace).withName(rcName).delete();	
			kube.pods().inNamespace(rc.getMetadata().getNamespace()).withLabels(rc.getSpec().getSelector()).delete();
		} catch(Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {
			if (null != kube)
				kube.close();
		}			
	}	
	
	/**
	 * 此方法需要在dp被删除后调用，才能删除rs
	 * @param apiServerUrl
	 * @param namespace
	 * @param rsList
	 */
	private static void deleteRs(String apiServerUrl, String namespace, List<ReplicaSet> rsList)
	{		 
		try {
			if (null == rsList || rsList.size() == 0) {
				return;
			}
			for(ReplicaSet replicaSet:rsList){
				String urlString = PropertiesUtils.getConfigValueCache("k8s.properties", "getReplicaSet.api");
				urlString = MessageFormat.format(urlString, apiServerUrl, namespace, replicaSet.getMetadata().getName());
				RestClientUtils.connect(urlString, new RestOperation() {

					@Override
					public Response request(WebTarget target) {
						return target.request().delete();
					}
				});
			}
		} catch (Exception e) {
			logger.error("catch exception when deleteRs ！", e);
		}
	}
	
	public static void deleteDp(String apiServerUrl, String namespace, String dpName)
	{		 
		KubernetesClient kube = null;
		try
		{				
			kube = getClient(apiServerUrl);				
			if(null == kube)						
				throw new NullPointerException(GETKUBEERROR);	
			Deployment dp = KubeUtils.getDp(kube, namespace, dpName);
			if(null == dp)
				return;
			
			List<ReplicaSet> rsList = getRssByDp(apiServerUrl, namespace, dpName);
			kube.extensions().deployments().inNamespace(namespace).withName(dpName).delete();	
			// 发现k8s在删除dp后并不会删除dp下的rs，所以在这里做手动删除
			deleteRs(apiServerUrl, namespace, rsList);
		} catch(Exception e) {			
			throw new RuntimeException(e.getMessage());
		} finally {
			if (null != kube)
				kube.close();
		}			
	}
	
	public static void scaleRc(String apiServerUrl, String namespace, String rcName, int replicas)
	{				
		if(!rcExist(apiServerUrl, namespace, rcName))
			throw new RuntimeException("Error : rc does not exist");
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			kube.replicationControllers().inNamespace(namespace).withName(rcName).scale(replicas);
			
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}	
	
	public static void scaleDp(String apiServerUrl, String nameSpace, String dpName, int replicas)
	{		
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == getDp(kube, nameSpace, dpName))
				throw new RuntimeException("Error : deployment not found in cluster");
			kube.extensions().deployments().inNamespace(nameSpace).withName(dpName).scale(replicas);
			
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}	
	public static boolean rcExist(String apiServerUrl, String namespace, String rcName)
	{
		return getRc(apiServerUrl, namespace, rcName) != null;
	}
	
	public static boolean dpExist(String apiServerUrl, String namespace, String dpName)
	{
		return getDp(apiServerUrl, namespace, dpName) != null;
	}
	
	public static ReplicationController getRc(String apiServerUrl, String namespace, String rcName)
	{	
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.replicationControllers().inNamespace(namespace).withName(rcName).get();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}
	
	public static Deployment getDp(String apiServerUrl, String namespace, String dpName)
	{	
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.extensions().deployments().inNamespace(namespace).withName(dpName).get();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}
	
	private static ReplicationController getRc(KubernetesClient kube, String namespace, String rcName)
	{				
		try
		{	
			if(null == kube)
				throw new RuntimeException("Error : kube is null");
			return kube.replicationControllers().inNamespace(namespace).withName(rcName).get();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} 		
	}
	
	private static Deployment getDp(KubernetesClient kube, String namespace, String dpName)
	{				
		try
		{	
			if(null == kube)
				throw new RuntimeException("Error : kube is null");
			return kube.extensions().deployments().inNamespace(namespace).withName(dpName).get();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} 		
	}

	public static ReplicationControllerList getRcList(String apiServerUrl, String namespace)
	{		
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.replicationControllers().inNamespace(namespace).list();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}		
	
	public static List<Pod> getPodByLabels(String apiServerUrl, String namespace, Map<String, String> labels) 
	{
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.pods().inNamespace(namespace).withLabels(labels).list().getItems();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
		
	public static void deletePodBylabels(String apiServerUrl, String namespace, Map<String, String> labels) {
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			kube.pods().inNamespace(namespace).withLabels(labels).delete();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
		
	}
	
	public static List<ReplicaSet> getRssByDp(String apiServerUrl, String namespace, String dpName) {
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			Deployment dp = kube.extensions().deployments().inNamespace(namespace).withName(dpName).get();
			if(null == dp)
				return null;
			return kube.extensions().replicaSets().inNamespace(namespace).withLabels(dp.getSpec().getSelector().getMatchLabels()).list().getItems();
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	/*
	 * @author : Shizhu.Peng 
	 * @createTime : Dec 19
	 */
	public static void addLabelToNode(String apiServerUrl, String nodeName, String key, String value) 
	{		
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.nodes().withName(nodeName).get())
				throw new RuntimeException("Error : node " + nodeName + " not found");
			kube.nodes().withName(nodeName).edit().editMetadata().addToLabels(key, value).endMetadata().done();	
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	/*
	 * @author : Shizhu.Peng 
	 * @createTime : Dec 19	  
	 * @Ps : it works correctly no matter key exists or not
	 */
	public static void deleteLabelOfNode(String apiServerUrl, String nodeName, String key) 
	{		
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.nodes().withName(nodeName).get())
				throw new RuntimeException("Error : node not found");
			kube.nodes().withName(nodeName).edit().editMetadata().removeFromLabels(key).endMetadata().done();	
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}	
	
	/*
	 * @author : Shizhu.Peng 
	 * @createTime : Dec 19
	 */
	public static List<Node> getNodeList(String apiServerUrl) 
	{
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.nodes().list())
				return null;
			return kube.nodes().list().getItems();	
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}	
	
	/*
	 * @author : Shizhu.Peng 
	 * @createTime : Dec 19
	 */
	public static List<Node> getNodeListWithLabel(String apiServerUrl, String key, String value) 
	{
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.nodes().withLabel(key, value).list().getItems();	// Potential Exception : kube.nodes().list() might be null
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	/*
	 * @author : Shizhu.Peng 
	 * @createTime : Dec 19
	 */
	public static Node getNodeByName(String apiServerUrl, String nodeName) 
	{
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			return kube.nodes().withName(nodeName).get();	
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	public static void addLabelToRc(String apiServerUrl, String namespace, String rcName, String key, String value) 
	{
		KubernetesClient kube = null;		
		try
		{
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.replicationControllers().withName(rcName))				
				throw new RuntimeException("Error : rc not found in k8s");
			kube.replicationControllers().inNamespace(namespace).withName(rcName).edit().editMetadata().addToLabels(key, value).endMetadata().done();	
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}

	/*
	 * 		Author			CreateTime		LastUpdateTime
	 * 		Shizhu.Peng		2017-02-16		2017-02-16
	 */
	public static void rollingUpdate(String apiServerUrl, String namespace, String rcName, String yamlContent) 
	{
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.replicationControllers().inNamespace(namespace).withName(rcName).get())				
				throw new RuntimeException("Error : rc not found in k8s");
			ReplicationController newRc = newRcByJson(kube, yamlContent);
			kube.replicationControllers().inNamespace(namespace).withName(rcName).rolling().replace(newRc);	
			
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}

	public static void replaceDp(String apiServerUrl, String namespace, String dpName, String yamlContent) 
	{
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.extensions().deployments().inNamespace(namespace).withName(dpName).get())				
				throw new RuntimeException("Error : dp not found in cluster");
			Deployment dp = newDpByJson(kube, yamlContent);
			kube.extensions().deployments().inNamespace(namespace).withName(dpName).replace(dp);
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}
	
	
	
	/*
	 * 		Author			CreateTime		LastUpdateTime
	 * 		Shizhu.Peng		2017-02-16		2017-02-16
	 */
	public static void rollingUpdateByKubectl(String apiServerUrl, String namespace, String rcName, String yamlContent) 
	{
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.replicationControllers().inNamespace(namespace).withName(rcName).get())				
				throw new RuntimeException("Error : rc not found in k8s");
			
			String yamlPath = String.format("/home/pshizhu/%s-rollingUpdate.yaml", rcName);
			FileIOUtil.writeToFile(yamlContent, yamlPath);
			String cmdRollingUpdate = String.format("kubectl --server=%s rolling-update %s -f %s", apiServerUrl, rcName, yamlPath);
			Process process = Runtime.getRuntime().exec(cmdRollingUpdate);
			process.waitFor();
			try {
				String cmdDeleteYamlFile = "rm -r " + yamlPath;
				Process process2 = Runtime.getRuntime().exec(cmdDeleteYamlFile);
				process2.waitFor();
			} catch (Exception e) {
				
			}			
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}
	
	/*
	 * 		Author			CreateTime		LastUpdateTime
	 * 		Shizhu.Peng		2017-02-21		2017-02-21
	 */
	public static List<Pod> getPodListByRc(String apiServerUrl, String namespace, String rcName) 
	{
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null == kube.replicationControllers().withName(rcName))				
				throw new RuntimeException("Error : rc not found in k8s");
			ReplicationController rc = kube.replicationControllers().inNamespace(namespace).withName(rcName).get();
			if(null == rc)
				throw new RuntimeException("Error : rc not found in k8s");
			PodList podList = kube.pods().inNamespace(namespace).withLabels(rc.getSpec().getSelector()).list();
			return null == podList ? null : podList.getItems();
			
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}		
	}
	
	public static void rcReplace(String apiServerUrl, String namespace, String rcName, String yamlConetent) 
	{		
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			ReplicationController rc = KubeUtils.newRcByJson(kube, yamlConetent);
			kube.replicationControllers().inNamespace(namespace).withName(rcName).replace(rc);						
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	public static boolean isYamlContentValid(String apiServerUrl, String yamlContent) {
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			if(null != KubeUtils.newRcByJson(kube, yamlContent))
				return true;
			return false;
		} catch(Exception e) {				
			return false;
		} finally {
			if(null != kube)
				kube.close();			
		}
	}
	
	
	public static void test(String yaml) 
	{
		String apiServerUrl = "132.122.239.3:8080";
		KubernetesClient kube = null;		
		try
		{			
			kube = getClient(apiServerUrl);
			if(null == kube)
				throw new NullPointerException(GETKUBEERROR);
			/*
			kube.replicationControllers().inNamespace("default").withName("pshizh-test2").edit()
			.editSpec().editTemplate().editMetadata().addToLabels("k1", "v1").endMetadata().editSpec().editContainer(0).editResources()
			.addToLimits("cpu", new Quantity("0.5"))
			.endResources().endContainer().endSpec().endTemplate().endSpec().done();
			*/
			/*
			ReplicationController rc = KubeUtils.newRcByJson(kube, yaml);
			kube.replicationControllers().inNamespace("default").withName("pshizh-test2").rolling().replace(rc);
			*/
//			Deployment deployment = KubeUtils.newDeploymentByJson(kube, yaml);
//			kube.extensions().deployments().inNamespace("default").withName("pshizh-deployment1")
			;
		//	kube.replicationControllers().inNamespace("default").withName("pshizh-test1").rolling().updateImage("132.122.239.2:5000/registry:2.3.1-0");
		//	kube.extensions().deployments().inNamespace("default").withName("pshizh-deployment1").h
		} catch(Exception e) {				
			throw new RuntimeException(e.getMessage());
		} finally {
			if(null != kube)
				kube.close();			
		}	
	}

}
